package cn.stacey.spring.ssm.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.stacey.spring.ssm.domain.AjaxResponse;
import cn.stacey.spring.ssm.domain.Category;
import cn.stacey.spring.ssm.domain.Post;
import cn.stacey.spring.ssm.service.CategoryService;
import cn.stacey.spring.ssm.service.PostService;

@Controller
public class PostController {
	Category category;
	@Autowired
	PostService postService;
	@Autowired
	CategoryService categoryService;
//http://localhost/springmvc/pages
	@RequestMapping("/pages/list")
	public ModelAndView list(HttpServletRequest request,Model model) {
		//检查请求转发到此处时有没有携带参数
//	System.out.println(request.getAttribute("id"));	
//	System.out.println(request.getAttribute("title"));
		//查询文章所有列表
	List<Post> posts=postService.findAll();
//	for(Post p:posts) {
//		System.out.println(p);
//	}
	//查询所有分类，初始化分类下拉列表
	List<Category> categories=categoryService.findAll();
	//跳转到文章列表对应的jsp页面
	ModelAndView mv=new ModelAndView();//跳到哪个页面（view），页面上需要显示哪些数据（model）
	mv.setViewName("posts");
	//posts对象会传给jsp页面
	//mv.addObject("posts",posts);
	model.addAttribute("posts",posts);
	model.addAttribute("categories",categories);
	return mv;
		
	}
	
//
	@RequestMapping("/post/findPage")
	public String findPage(
			@RequestParam(name="page",defaultValue="1") Integer page,
			@RequestParam(name="size",defaultValue="10") Integer size,
			Model model
			) {
		
			AjaxResponse<Post> pageData = postService.findPage(page, size);
			//根据文章的总条数   和   每页多少条  计算总共需要多少页
			int totalPage=(pageData.getCount()-1)/size+1;
			model.addAttribute("posts",pageData.getData());
			model.addAttribute("currentPage",page);
			model.addAttribute("totalPage",totalPage);
				return "posts";
		
	}

	//返回json序列化
	@RequestMapping("/pages/jsonlist")
	@ResponseBody
	public List<Post> jsonlist() {
		//查询文章所有列表
	List<Post> posts=findPosts();
	return posts;	
		
	}
	
	
	@RequestMapping("/pages/find_by_id")
	@ResponseBody
	public Post findById(int id) {
		Post post= new Post();
		post.setId(id);
		post.setContent("中文");
		post.setTitle("标题");
		post.setCreated(new Date());
		Category c=new Category();
		c.setId(1);
		c.setName("分类1");
		c.setPriority(2);
		post.setCategory(c);
		return post;
		
	}
	public List<Post> findPosts() {
		List<Post> posts=new ArrayList<>();
		for(int i=0;i<10;i++) {
			Post p=new Post();
			p.setId(i);
			p.setTitle("title"+i);
			p.setContent("content"+i);
			p.setCreated(new Date());
			posts.add(p);
		}
		return posts;
	}
	
	//mapping  a标签里面的edit/form/4路径
	@RequestMapping("/post/edit_form")
	public String eidtForm(
			@RequestParam("id") int id,
			
			Model model,Post p) {
		//编辑的时候只带一个id过去，再根据Id把id对应的标题内容查一遍，显示到编辑列表
		//Integer id = Integer.valueOf(id1);
		System.out.println(id);
		//p.setId(id);
		
		List<Category> categories=categoryService.findAll();
		model.addAttribute("categories",categories);
		//根据id查内容
		Post post = postService.getByIdWithCategory(id);
		model.addAttribute("post",post);
		//注释掉下面这句话也没关系??
		//model.addAttribute("id",id);
		return "post_form";
	}
	//更新文章,对应form表单的action="update" ，?相对路径直接拼到上一个url  /edit_form/{id}后面? 
	@RequestMapping("/edit_form/update")
	public String update(
		Model model,Post p) {

		System.out.println(p);
		
		postService.update1(p.getId(), p);
		//更新之后重新查找一遍
		List<Post> posts = postService.findAll();
		model.addAttribute("posts",posts);
		return "posts";
	}
	
	
	
	//mapping  a标签里面的edit/form/4路径
		@RequestMapping("/delete_form")
		public String deleteForm(
				@RequestParam("id") int id,
				Model model,Post p) {
			System.out.println(id);
//			p.setId(id);
			postService.deleteById(id);
			//删除之后重新查找一遍
			List<Post> posts = postService.findAll();
			//下面的"posts"是一个名字与前端的items中的posts对应
			model.addAttribute("posts",posts);
			return "posts";
		}
		
		
	
	
	@RequestMapping("/pages/edit")
	public String edit(Post p,Model model,@RequestParam("upLoadFile") MultipartFile file) {
		//把请求跳转到一个jsp页面
//		List<Post> posts=service.findAll();
//		model.addAttribute("posts",posts);
//		return "posts";

		//请求重定向(参数传递方法)
		//直接把参数放到model里面
		model.addAttribute("id",p.getId());
		model.addAttribute("title",p.getTitle());
		//文件名字
		String fileName = file.getOriginalFilename();
		System.out.println("上传文件名:"+fileName);
		System.out.println("文件大小："+file.getSize());
		//文件复制到磁盘某个路径
		try {
			file.transferTo(new File("D:\\"+fileName));
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//请求转发
		return "forward:/pages/list.action";
		//重定向
//		return "redirect:/pages/list.action";

		
	}
	
	@RequestMapping("/post/insert")
	public String insert(Post p) {
		postService.insert(p);
		return "success";
		
	}
	//根据文章标题，分类创建时间查找	文章
	@RequestMapping("/posts/search")
	public String search(
			Post post,
			@RequestParam(name="page",defaultValue="1") Integer page,
			@RequestParam(name="size",defaultValue="10") Integer size,
			Model model)
			
	{
		//参数回显  （查询之后输入的文章标题，文章分类创建时间应该还在输入框中）
		if(!StringUtils.isEmpty(post.getTitle())) {
			model.addAttribute("title",post.getTitle());
		}
		if(!StringUtils.isEmpty(post.getCategory())) {
			model.addAttribute("cid",post.getCategory().getId());
		}
		if(!StringUtils.isEmpty(post.getCreated())) {
			model.addAttribute("created",post.getCreated());
		}
		List<Category> categories = categoryService.findAll();
		model.addAttribute("categories", categories);
//			List<Post> posts = postService.search(post);
				String title = post.getTitle();
	//post.getCid与post.getCategory().getId()区别
			Integer cid = post.getCategory()==null?null:post.getCategory().getId();
			if(cid==-1) {
				cid=null;
			}
			Date created = post.getCreated();
			 AjaxResponse<Post> searchPage = postService.searchPage(title, cid, created, page, size);
			int totalPage=(searchPage.getCount()-1)/size+1;
			model.addAttribute("posts",searchPage.getData());
			model.addAttribute("currentPage",page);
			model.addAttribute("totalPage",totalPage);
			return "posts";
		
	}
	
	//批量删除
	@RequestMapping("/post/deleteBatch")
	public String deleteBatch(String[] ids,Model model) {
		postService.deleteBatch(ids);
		List<Post> posts = postService.findAll();
		model.addAttribute("posts",posts);
		return "posts";
		
	}
	
	
}





